<template>
  <div class="callreport" v-loading="loading">
    <div class="top">
      <div class="search">
        <div class="contition">
          <div class="wrap_time">
            <date-time type="other_half_hour" @changeType="changeType" :query="query" @isFold="isShowFold"
              :isTimePeriod="true" ref="timeChild" :isOther="true"></date-time>
            <el-button type="primary" class="primary_btn fr find" @click.stop='search'>{{ $t('public.search2') }}
            </el-button>
            <div class="clear"></div>
          </div>
          <div class="wrap_drop">
            <unfold :isShow="isFold" :title="[]">
              <template slot="unfoldSlot">
                <div class="serve">
                  <span class="colo">{{ $t('monitor.serviceNum') }}：</span>
                  <servicesNoFilter v-if="isViewShow" :serviceNos="serviceNos" :checkedNos="checkedNos"
                    @serveNoFilterChange="serveNoFilterChange"
                    style="width:220px;display: inline-block;margin-right:20px;"></servicesNoFilter>
                  <el-checkbox v-model.trim="checkAll" @change="handleCheckAllChange">{{ $t('public.checkAll') }}
                  </el-checkbox>
                  <el-checkbox v-model.trim="query.delete_ServerNo">{{ $t('report.deletedServe') }}</el-checkbox>
                  <el-checkbox-group v-model.trim="checkedNos" @change="handleCheckedCitiesChange">
                    <div class="serviceDisplayWrap" v-for="(one, index) in serviceNos" :key="index">
                      <el-checkbox :label="one.Exten">{{ one.Exten }}
                        <span v-if="one.DisplayName">
                          [<span :title="one.DisplayName" class="serviceDisplayName ellipsis">
                            {{ one.DisplayName }}</span>]</span>
                      </el-checkbox>
                    </div>
                  </el-checkbox-group>
                </div>
              </template>
            </unfold>
          </div>
        </div>
      </div>
      <affix :label="$t('report.callInSurvey')"></affix>
      <div class="situation">
        <el-row>
          <el-col v-for="(item, index) in situation" :span="8" :key="index">
            <span class="sum_name">{{ item.name }}</span>
            <span class="sit_num">{{ item.value }}</span>
          </el-col>
        </el-row>
      </div>
      <affix :label="$t('report.relaycallInRe')"></affix>
    </div>
    <div :id="id">
      <el-row class="ichars">
        <highcharts :options="options24out"></highcharts>
        <div class="notes">
          <span class="light">{{ $t('report.hicharsNotes') }}: <span></span>{{ $t('report.hicharsLight') }}</span>
          <span class="dark"><span></span>{{ $t('report.hicharsDark') }}</span>
        </div>
      </el-row>
      <div class="tab">
        <div class="export">
          <el-button class="primary_btn fr formal" v-if="configFormula" @click="$refs.formulaEditorDialog.open()">
            {{ $t('report.formalTitle') }}</el-button>
          <el-button class="primary_btn fr" v-if="!configHeaderBool" v-on:click.stop="config">
            {{ $t('report.setHeaderConfig') }}</el-button>

          <!-- <el-button class="primary_btn fr report_excel_btn"
              v-if="$store.getters.exportFromEnd"
              v-on:click.stop="exportExcel"
            >{{$t('report.exportXls')+($store.state.xlsxExportMode==='Both'?'(旧)':'')}}</el-button> -->
          <el-tooltip class="item" content="点击此处可导出时间范围下每日的时间段呼入数据。" effect="dark" placement="bottom">
            <el-button class="primary_btn fr" style="margin: 0 10px 0 0" v-show="isShowDetailExport"
              v-on:click.stop="exportDetailExcel()">{{ $t('report.exportDetailXls') }}
              <span class="tip"><i class="iconfont icon-tixingweizhi"
                  style="border: none;font-size: 10px;color: #459ae9;"></i></span>
            </el-button>
          </el-tooltip>
          <el-button class="primary_btn fr report_excel_btn" v-on:click.stop="exportXlsx">{{ $t('report.exportXls') }}
          </el-button>

          <el-button class="primary_btn fr pdf" v-on:click.stop="exportPdf">{{ $t('report.exportPDF') }}</el-button>
          <el-select @change="search" v-if="$refs.timeChild && $refs.timeChild.form.timeType === 'day'"   class="fr"
              size="mini" v-model="query.granularity" style="height:30px;width:120px;">
                        <el-option :label="$t('report.oneHourTrend')" value="1h"></el-option>
                        <el-option :label="$t('report.halfHourTrend')" value="0.5h"></el-option>
                      </el-select>
        </div>
        <div class="deploy">
          <!-- <i class="iconfont icon-peizhi"></i>
            <span class="tex" @click.stop="config">{{$t('report.setHeaderConfig')}}</span> -->
          <el-collapse accordion>
            <el-collapse-item>
              <template slot="title">
                <span class="fl explain">{{ $t('report.toggleInstructe') }}</span>
              </template>
              <div>
                <p style="color: #ccc;
    margin: 5px 0;
    font-size: 12px;">{{ $t('report.callHint') }}</p>
                {{ $t('report.callIvr') }}<br>
                {{ $t('report.callAnswerNum') }}<br>
                {{ $t('report.callMesLeaveNum') }}<br>
                {{ $t('report.callRingNotAnswerNum') }}<br>
                {{ $t('report.callQueueUpNum') }}<br>
                {{ $t('report.callBlankRedNum') }}<br>
                {{ $t('report.callAllHappenNum') }}<br>
                {{ $t('report.callTotalNum') }}<br>
                9.{{ $t('report.IncomingTimeLength') }}<br>
                10.{{ $t('report.IncomingRingingTimeLength') }}<br>
                11.{{ $t('report.inRepeatBy24hCount') }}<br>
                12.{{ $t('report.inRepeatBy48hCount') }}<br>
                13.{{ $t('report.CustomerFastHangUp') }}
                <p class="custom_alg">{{ $t('report.ziDingYi') }}：</p>
                <p v-for="(item, index) in formulas" :key="item.name">
                  {{ index + 14 }}.{{ item.formulaInstr }}
                </p>
              </div>
            </el-collapse-item>
          </el-collapse>
        </div>
        <report-table :data="serveNumData" :sum="sum" :config="[...headOptions.Config, ...formulasConfig]">
        </report-table>
      </div>
    </div>
    <el-dialog :close-on-click-modal="false" modal-append-to-body lock-scroll top="10%"
      :title="$t('report.reportExportHelp')" :visible.sync="dialogVisible" width="30%">
      <span>{{ $t('report.reportExportTipTitle') }}</span>
      <span slot="footer" class="dialog-footer">
        <el-button class="primary_btn" @click="dialogVisible = false">{{ $t('public.cancel') }}</el-button>
        <el-button class="primary_btn" type="primary" @click="confirm">{{ $t('public.confirm') }}</el-button>
      </span>
    </el-dialog>
    <!--<div class="box" v-if="isShow"></div>-->
    <header-option v-show="isShow" :show="isShow" :option="headOptionsShow" type="call_report_relay_time"
      v-on:close="close" :headCustom="formulasConfig"></header-option>
    <!-- 自定义公式组件 -->
    <FormulaEditorDialog ref="formulaEditorDialog" :headOptionsConfig="headOptions.Config"
      @closeFormulaDialog="closeFormulaDialog" reportName="呼入时间趋势报表" :reportType="id" />
  </div>
</template>
<script>
import affix from '../../../ui-modules/affix/Affix.vue'
import unfold from '../../../ui-modules/unfold/index.vue'
import dateTime from '../base/datetime.vue'
import headerOption from '../base/headerOption.vue'
import { exportReportPdf, checkTime, searchTime, colorConfigArr, headOptionsToXlsxHeaders, mixData } from '@/utils/reportUtils.js'
import { getCache, deepClone, getCallTimeLength, optionTimeTypeCheck, isHasFunc } from '@/utils/m7Utils.js'
import reportTable from '../base/reportTable.vue'
import servicesNoFilter from '../base/servicesNoFilter.vue'
import * as XlsxUtil from 'src/utils/XlsxUtil.umd.js'
import { sortBy } from 'lodash'
import FormulaEditorDialog from '../base/FormulaEditorDialog.vue'
export default {
  name: 'CallInReport',
  data() {
    return {
      configFormula: true, // 自定义公式的权限
      dateType: 'day',
      isFold: false, // 是否展开查询条件开关
      situation: [], // 概况渲染数据
      loading: false, // 请求数据遮罩开关
      isViewShow: false, // 避免服务号加载不出来设置得变量
      id: 'call_report_relay_time', // 需传参数id
      query: {
        reportType: 'call_report_relay_time',
        delete_ServerNo: false,
        delete_ServerNos: '',
        granularity: '0.5h', // 时间趋势
      },
      dialogVisible: false, // 导出pdf开关
      checkAll: true, // 全选开关
      checkedNos: [], // 绑定服务号数据
      headOptionsShow: {}, // 配置表头需传参数
      headOptions: {
        Config: []
      },
      serviceNos: [], // 渲染服务号数据
      isShow: false, // 配置表头弹层开关
      serveNumData: [], // 渲染表格数据
      resData: [], // 返回数组暂存
      sum: [{ ReportTime: this.$t('report.total') }], // 表格合计数据
      options24out: { // hcharts图表配置
        chart: {
          type: '',
          animation: false
        },
        colors: colorConfigArr,
        xAxis: {
          categories: []
        },
        yAxis: {
          gridLineColor: '#e6e6e6',
          allowDecimals: false,
          title: {
            text: ''
          }
        },
        title: {
          text: this.$t('report.relaycall')
        },
        legend: {
          align: 'center',
          verticalAlign: 'top',
          x: 0,
          y: 20
        },
        tooltip: {
          shared: true
        },
        plotOptions: {
          column: {
            stacking: 'normal'
          },
          series: { animation: false }
        },
        credits: { enabled: false },
        series: []
      },
      isSearch: false,
      formulas: [] // 公式数据
    }
  },
  components: {
    affix,
    unfold,
    dateTime,
    headerOption,
    reportTable,
    servicesNoFilter,
    FormulaEditorDialog
  },
  methods: {
    // 子组件切换时间类型传上来得方法 触发计算属性
    changeType(type) {
      this.dateType = type
    },
    // 自定义公式弹窗关闭外抛事件
    closeFormulaDialog() {
      this.isSearch = false
      this.$store.dispatch('queryFetchFormula', { type: this.id }).then((resp) => {
        if (resp.success) {
          this.formulas = resp.data.Formulas
        }
      })
    },
    // 查询条件展开收起方法
    isShowFold(bool) {
      this.isFold = bool
    },
    // 获取查询条件
    getSearchQueryData() {
      // 判断服务号是否为空
      if (this.checkedNos.length === 0 && this.query.delete_ServerNo === false) {
        this.isServerNum()
        return
      }
      // 完善查询条件
      let data = {
        reportType: 'call_report_relay_time',
        account: this.$store.state.session.user.account
      }
      let self = this
      self.serviceNos.forEach(function (item) {
        if (self.checkedNos.indexOf(item.Exten) >= 0) {
          self.query['ServiceNo_' + item.Exten] = true
        } else {
          self.query['ServiceNo_' + item.Exten] = false
        }
      })
      let isWeek = this.$refs.timeChild.form.timeType
      let myQuery = deepClone(this.query)
      // 判断是否为周报查询 周报查询更改查询类型
      if (isWeek === 'week') {
        myQuery.timeType = 'other'
        let message = checkTime(myQuery.StartTime, myQuery.EndTime, false, true)
        if (message !== true) {
          this.$message.error(this.$t(message))
          return
        }
      } else if (myQuery.timeType === 'other_half_hour') {
        // 校验类型与时间
        let message = checkTime(myQuery.StartTime, myQuery.EndTime, false, false)
        if (message !== true) {
          this.$message.error(this.$t(message))
          return
        }
      }
      // 时间插件返回的是小写的timeType转大写的
      myQuery.TimeType = myQuery.timeType
      delete myQuery.timeType
      data['query'] = myQuery
      return data
    },
    // 获取新的表格数据ServeNumData，抽取共同
    getServeNumDataAndSum(myQuery) {
      let headOptions = this.headOptions
      let tempData = deepClone(mixData(this.resData, this.formulas))
      let sum = { ReportTime: this.$t('report.total') }
      // 计算合计
      for (let i in tempData) {
        let item = tempData[i]
        if (myQuery.TimeType === 'year') {
          item.ReportTime = item.MonthID
          delete item.MonthID
        } else if (myQuery.TimeType === 'month') {
          item.ReportTime = item.DayID
          delete item.DayID
        } else if ((myQuery.TimeType === 'other_half_hour') && myQuery.timePeriod) {
          //    查询方式为  自定义 或  日报  并且 定时间段统计  则更换 时间 渲染的字段
          item.ReportTime = item.DayID
          delete item.DayID
        } else if (myQuery.TimeType === 'other') { // 周报查询按天展示
          item.ReportTime = item.DayID
        }
        for (let j in item) {
          if (sum[j] === undefined) {
            sum[j] = 0
          }
          if (j !== 'ReportTime') {
            sum[j] += item[j]
          }
        }
        headOptions.Config.forEach((option, index) => {
          if (option.timeType && option.timeType === 'hhmmss') {
            item[option.name] = getCallTimeLength(item[option.name])
          } else if (option.timeType && option.timeType === 'second') {
            item[option.name] = Math.round(item[option.name]) + 's'
          }
        })
      }
      sum = mixData([sum], this.formulas)
      console.log(sum, '呼入');


      headOptions.Config.forEach((option, index) => {
        if (option.timeType && option.timeType === 'hhmmss') {
          sum[0][option.name] = getCallTimeLength(sum[0][option.name])
        } else if (option.timeType && option.timeType === 'second') {
          sum[0][option.name] = Math.round(sum[0][option.name]) + 's'
        } else if (option.timeType && option.timeType === 'percent') {
          sum[0][option.name] = sum[0][option.name] + '%'
        }
      })
      // 使table开始渲染的时间按顺序排列
      return {
        serveNumData: sortBy(tempData, 'ReportTime'),
        sum: sum
      }
    },
    // 查询的方法
    search() {
      var queryData = this.getSearchQueryData()
      console.log(queryData)
      if (!queryData) {
        return
      }

      var myQuery = queryData.query
      this.loading = true
      this.$store.dispatch('queryCallRelayTimeReport', queryData).then((res) => {
        if (this.$store.state.report.customExportData) {
          res = JSON.parse(this.$store.state.report.customExportData)
        }
        if (!res.success) {
          this.loading = false
          return
        }
        this.loading = false
        this.isSearch = true
        this.$store.dispatch('queryFetchFormula', { type: this.id }).then((resp) => {
          if (resp.success) {
            this.formulas = resp.data.Formulas
            this.headOptions = optionTimeTypeCheck(res.tableHeader)
            this.resData = res.data
            //  图表标题 加入 定时段的 时间
            let highchartsTitle = ''
            if (myQuery.timePeriod) {
              let timePeriodStartStr = myQuery.timePeriodStart || '00:00'
              let timePeriodEndStr = myQuery.timePeriodEnd || '23:59'
              highchartsTitle = '(' + timePeriodStartStr + '~' + timePeriodEndStr + ')'
            }
            this.options24out.title.text = this.$t('report.relaycall') + highchartsTitle

            var { sum, serveNumData } = this.getServeNumDataAndSum(myQuery)

            this.sum = sum
            this.serveNumData = serveNumData

            // 渲染hichars 内容
            let series4high = {}
            this.options24out.xAxis.categories = []
            // 添加渲染图表数据
            for (let i in this.serveNumData) {
              let item = this.serveNumData[i]
              this.options24out.xAxis.categories.push(item.ReportTime)
              for (let j in item) {
                if (series4high[j] === undefined) {
                  series4high[j] = []
                }
                if (j !== 'ReportTime' && j !== 'IncomingTimeLength' && j !== 'IncomingRingingTimeLength') {
                  series4high[j].push(item[j])
                } else {
                  delete series4high[j]
                }
              }
            }
            this.situation = []
            this.options24out.series = []

            let tempData = deepClone(res.data)
            for (let i in res.tableHeader.Config) {
              let item = res.tableHeader.Config[i]
              // 渲染概况
              if (tempData.length !== 0) {
                for (let j in this.sum[0]) {
                  if (j === item.name && j !== 'ReportTime' && j !== 'IncomingTimeLength' && j !== 'IncomingRingingTimeLength') {
                    this.situation.push({ name: item.displayname, value: this.sum[0][j] })
                    break
                  }
                }
              } else if (item.name !== 'ReportTime' && item.name !== 'IncomingTimeLength' && item.name !== 'IncomingRingingTimeLength') {
                this.situation.push({ name: item.displayname, value: 0 })
              }
              if (item.name !== 'ReportTime' && item.name !== 'IncomingTimeLength' && item.name !== 'IncomingRingingTimeLength') {
                this.options24out.series.push({
                  name: item.displayname,
                  data: series4high[item.name]
                  // visible: false
                })
              }
            }
          }
        })
      })

    },
    // 关闭配置表头弹窗,如果点击保存则查询重新渲染数据
    close(data) {
      this.isShow = false
      if (data === 'save') {
        this.search()
      }
    },
    // 服务号为空提示文案执行方法
    isServerNum() {
      this.$message.error(this.$t('report.searchBathnos'))
    },
    // 导出PDF
    exportPdf() {
      this.dialogVisible = true
    },
    // 确认导出pdf执行的方法
    confirm() {
      this.dialogVisible = false
      exportReportPdf({ title: this.$t('report.callInReport') + searchTime(this.query), id: this.id })
    },
    exportDetailExcel() {
      let self = this
      this.checkedNos.forEach(function (item) {
        self.query['ServiceNo_' + item] = true
      })
      let isWeek = this.$refs.timeChild.form.timeType
      let myQuery = deepClone(this.query)
      if (isWeek === 'week') {
        myQuery.timeType = 'other'
        let message = checkTime(myQuery.StartTime, myQuery.EndTime, false, true)
        if (message !== true) {
          this.$message.error(this.$t(message))
          return
        }
      } else if (myQuery.timeType === 'other_half_hour') {
        // 校验类型与时间
        let message = checkTime(myQuery.StartTime, myQuery.EndTime, false, false)
        if (message !== true) {
          this.$message.error(this.$t(message))
          return
        }
      }
      myQuery.TimeType = myQuery.timeType
      delete myQuery.timeType
      myQuery.reportType = 'call_report_relay_time'
      myQuery.accountId = this.$store.state.session.user.account
      myQuery.type = 'ReportRelayTimeExport'
      myQuery.user = this.$store.state.session.user._id
      let data = {
        Method: 'exportIncomingTimeTrendDetails',
        Query: myQuery
      }
      this.$store.dispatch('exportCallRelayTimeReport', data).then(() => {
      })
    },
    // 导出表格数据执行的方法(后端)
    exportExcel() {
      let self = this
      this.checkedNos.forEach(function (item) {
        self.query['ServiceNo_' + item] = true
      })
      let isWeek = this.$refs.timeChild.form.timeType
      let myQuery = deepClone(this.query)
      if (isWeek === 'week') {
        myQuery.timeType = 'other'
        let message = checkTime(myQuery.StartTime, myQuery.EndTime, false, true)
        if (message !== true) {
          this.$message.error(this.$t(message))
          return
        }
      } else if (myQuery.timeType === 'other_half_hour') {
        // 校验类型与时间
        let message = checkTime(myQuery.StartTime, myQuery.EndTime, false, false)
        if (message !== true) {
          this.$message.error(this.$t(message))
          return
        }
      }
      myQuery.TimeType = myQuery.timeType
      delete myQuery.timeType
      myQuery.reportType = 'call_report_relay_time'
      myQuery.accountId = this.$store.state.session.user.account
      myQuery.type = 'ReportRelayTimeExport'
      myQuery.user = this.$store.state.session.user._id
      let data = {
        Method: 'exportRelayTimeReport',
        Query: myQuery
      }
      this.$store.dispatch('exportCallRelayTimeReport', data).then(() => {
      })
    },
    // 导出表格数据执行的方法(前端)
    exportXlsx() {
      var queryData = this.getSearchQueryData()

      if (!queryData) {
        return
      }

      var myQuery = queryData.query || deepClone(this.query)
      this.loading = true
      this.$store.dispatch('queryCallRelayTimeReport', queryData).then((res) => {
        if (this.$store.state.report.customExportData) {
          res = JSON.parse(this.$store.state.report.customExportData)
        }
        if (!res.success) {
          this.loading = false
          return
        }
        this.loading = false
        var headOptions = optionTimeTypeCheck(res.tableHeader)

        var { sum, serveNumData } = this.getServeNumDataAndSum(myQuery)
        if (serveNumData.length === 0) {
          sum = []
        }
        var tableData = serveNumData.concat(sum)

        var headers = headOptionsToXlsxHeaders([...headOptions.Config, ...this.formulasConfig])

        var dh = XlsxUtil.getDownloadHelper(headers, tableData)
        var timeStamp = XlsxUtil.dateFormat(new Date(), 'yyyy-MM-dd hh-mm-ss')
        dh.download(this.$t('report.callInReport') + timeStamp)
      })
    },
    // 控制全选
    handleCheckAllChange(event) {
      this.checkedNos = []
      if (this.checkAll === true) {
        this.serviceNos.forEach((i) => {
          this.checkedNos.push(i.Exten)
        })
      }
    },
    // 选择多选是判断 多选选框是否勾选
    handleCheckedCitiesChange(value) {
      if (this.checkedNos.length === this.serviceNos.length) {
        this.checkAll = true
      } else {
        this.checkAll = false
      }
    },
    // 获取表头数据
    config() {
      this.$store.dispatch('getReportTableHeader', 'call_report_relay_time').then((res) => {
        this.headOptionsShow = optionTimeTypeCheck(res)
        this.isShow = !this.isShow
      })
    },
    // 服务号筛选  后加功能
    serveNoFilterChange(val) {
      this.checkedNos = val
      this.handleCheckedCitiesChange()
    }
  },
  computed: {
    // 是否展示导出详细excel
    isShowDetailExport() {
      let type = ['week', 'month']
      return type.includes(this.dateType)
    },
    // 判断是否展示配置表头
    configHeaderBool() {
      return this.$store.state.report.setConfigHeaderBool
    },
    showview() {
      return this.$refs.timeChild && this.$refs.timeChild.form.timeType === 'day'
    },
    // 自定义表头
    formulasConfig() {
      return this.formulas.map((d, i) => {
        return {
          displayname: d.displayname,
          name: d.name,
          order: d.order,
          show: d.show,
          timeType: 'none',
          digits: d.digits,
          type: d.type
        }
      })
    }
  },
  watch: {
    // 监测自定义公式变化 更新数据
    formulas(cur, old) {
      if (this.isSearch) {
        return
      }
      if (!this.serveNumData || this.serveNumData.length === 0) {
        return
      }
      var queryData = this.getSearchQueryData()
      if (!queryData) {
        return
      }
      console.log(queryData, 'ysyssyysysysy');
      var myQuery = queryData.query
      var { sum, serveNumData } = this.getServeNumDataAndSum(myQuery)
      this.sum = sum
      this.serveNumData = serveNumData
    }
  },
  beforeMount() {
    if (isHasFunc('func_forbid_config_formula', this.$store.state.session.user)) {
      this.configFormula = false // 没有自定义公式的配置权限
    }
    this.$store.dispatch('getCache', { type: 'serviceNo', loadFromServer: true }).then(() => {
      this.serviceNos = getCache('serviceNo')
      this.isViewShow = true
      this.handleCheckAllChange()
      this.search()
    })
  }
}
</script>
<style lang="stylus" scoped>
  @import "../../../../assets/common.styl"
  .callreport
    .tip
      cursor pointer
      display inline-block
      height 16px
      width 16px
      border 1px solid #459ae9
      text-align center
      line-height 15px
      border-radius 50%
      margin 0px 0 0 6px
    .formal
      margin-left 10px
    .box
      width 300px
      height 300px
      position absolute
      border 1px solid $cf-gray0
      background #0f0
      left 50%
      margin-left -150
      top 30px
      z-index 10
    .serve
      margin 14px 0 0 0px
    .serviceDisplayWrap
      display inline-block
      width 170px
      .serviceDisplayName
        max-width 48px
        display inline-block
        position relative
        top 5px
  .el-checkbox-group
    margin-top 14px
    .col
      display inline-block
      width 56px
  .el-col-1
    height 36px
    line-height 36px
</style>
